/**
 * @function 附件下载
 * @param {String} url  请求链接
 * @param {String} fileCode  附件编码
 * @param {Object}  params 请求参数
 */
export const download = (url, fileCode, token = null, fileName = null, params = null, callback = null) => {
    let downData = new FormData();
    downData.append('fileCode',fileCode);
    if (params !== null) {
        for (let key in params) {
            downData.append(key, params[key]);
        }
    }
    let xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Authorization',_getLocalStore('token'))
    xhr.setRequestHeader('responseType','base64');
    xhr.onreadystatechange =  (res)=> {
        if (xhr.readyState == 4 && xhr.status == 200) {
            const data = JSON.parse(xhr.response);
            const name = fileName == null ? (new Date().getTime() + '.zip') : fileName;
            const fileExtension = getFileType(name);
            base64ToFile(`data:${fileExtension};base64,`+data.data, name, callback)
        }
      };
      xhr.onerror =  (error) =>{
        reject(error);
      };
      xhr.send(downData);
};

export const downloadfile = (url, fileName = null, params = null,token = null) => {
    debugger
    let downData = new FormData();
    if (params !== null) {
        for (let key in params) {
            downData.append(key, params[key]);
        }
    }
    let xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Authorization', token);
    xhr.onreadystatechange =  (res)=> {
        if (xhr.readyState == 4 && xhr.status == 200) {
            const data = JSON.parse(xhr.response);
            const name = fileName == null ? (new Date().getTime() + '.zip') : fileName;
            const fileExtension = getFileType(name);
            base64ToFile(`data:${fileExtension};base64,`+data.data, name)
        }
    };
    xhr.onerror =  (error) =>{
        this.$message.error(error.toString())
    };
    xhr.send(downData);
};
// 将base64转化为文件
function base64ToFile(base, name, callback = null) {
    const arr = base.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    const url = window.URL.createObjectURL(new Blob([u8arr], { type: mime }));
    if (typeof callback == 'function') {
        callback({url, base64: base});
    } else {
        if (window.navigator.msSaveBlob) {
            // for ie 10 and later
            try {
                const blobObject = new Blob([u8arr], { type: mime });
                window.navigator.msSaveBlob(blobObject, name );
            } catch (e) {
                console.log(e);
            }
        } else {
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', name);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link); // 下载完成移除元素
            window.URL.revokeObjectURL(url); // 释放掉blob对象
        }
    } 
  }
  /**
   *
   * @param {*} fileExtension
   */
  function getFileType(fileExtension) {
    if (fileExtension.indexOf(".") != -1) {
        var fileName_arry = fileExtension.split('.');
        //获取截取的最后一个字符串，即为后缀名
        fileExtension = fileName_arry[fileName_arry.length - 1];
    }
    /*获取打开的类型*/
    let mimeType = '';
    switch (fileExtension) {
        case 'txt':
            mimeType = 'text/plain';
            break;
        case 'docx':
            mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
            break;
        case 'doc':
            mimeType = 'application/msword';
            break;
        case 'pptx':
            mimeType = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
            break;
        case 'ppt':
            mimeType = 'application/vnd.ms-powerpoint';
            break;
        case 'xlsx':
            mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            break;
        case 'xls':
            mimeType = 'application/vnd.ms-excel';
            break;
        case 'zip':
            mimeType = 'application/x-zip-compressed';
            break;
        case 'rar':
            mimeType = 'application/octet-stream';
            break;
        case 'pdf':
            mimeType = 'application/pdf';
            break;
        case 'jpg':
            mimeType = 'image/jpeg';
            break;
        case 'png':
            mimeType = 'image/png';
            break;
        case 'apk':
            mimeType = 'application/vnd.android.package-archive';
            break;
        default:
            mimeType = 'application/' + fileExtension;
            break;
    }
    return mimeType;
}